﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Maticsoft.Common;
using DQYT.HTDZ.DBUtility;
using DQYT.HTDZ.BusinessService;
using System.Xml;
using System.Text;
using System.Drawing;
using DQYT.HTDZ.Common;
using DQYT.HTDZ.BLL;

namespace DQYT.HTDZ.Web.Views.SJCJDB
{
    public partial class ConfigDataSource : System.Web.UI.Page
    {
        #region//本页变量
        private int CurStep;                        //当前步骤
        private IConfigurature dbConf;
        private string[] congInfo;
        private string curTableName;                           // 当前表名
        private string curUserID;                               //当前用户id
        //private bool isSelect=false;                          //是否是点击下拉菜单而刷新的页面
        List<string> sList = new List<string>();        //本地表字段
        //List<string> lstNotNullFields = new List<string>();       //服务器数据库表的不为空字段
        List<string> lstSQL = new List<string>();                 //临时存放拼接sql语句的list
        private string sSrcTableSQL;                              //本地表查询SQL
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            #region
            if (!Page.IsPostBack)
            {
                //Wizard1.ActiveStepIndex = 0;
                CurStep = 1;
                this.Session.Add("CurStep", (object)(CurStep));

                //VisibleEnabled(1);
                InitDataSource();
                this.Session.Add("isSelect", "0");                      //是否是点击下拉菜单而刷新的页面
                //this.Session.Add("notnullfields", lstNotNullFields);            //不允许为空的字段，这个应在上一个页面添加的，先暂时添加在这
                this.Session.Add("srctablesql", "");                             //本地表查询sql
                this.Session.Add("srcfields", sList);                           //本地表字段list
                this.Session.Add("lstsql", lstSQL);                              //存放拼接sql语句的list
            }
            //curUserID = this.Session["UserID"].ToString();//临时屏蔽
            // curTableName = this.Session["  "].ToString();//临时屏蔽
            curUserID = "1002";
            curTableName = "BDDATESOURSE";

            //if (Convert.ToInt32(this.Session["CurStep"].ToString()) ==2 )
            if (Wizard1.ActiveStepIndex == 1 && ddlDBTable.SelectedValue.Trim() != "")
            {
                ConnectionDB(this.ddlDBSource.SelectedValue.ToString());
                //为了给后台传递表名
                List<string> aList = new List<string>();
                aList = dbConf.GetColumnsScama(ddlDBTable.SelectedValue.ToString());
            }
            #endregion
        }


        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            #region
            CurStep = Convert.ToInt32(this.Session["CurStep"].ToString()) - 1;
            this.Session["CurStep"] = (object)CurStep;
            //VisibleEnabled(CurStep);
            #endregion
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            #region
            bool isConnection;

            CurStep = Convert.ToInt32(this.Session["CurStep"].ToString()) + 1;
            this.Session["CurStep"] = (object)CurStep;
            //VisibleEnabled(CurStep);
            if (CurStep == 2)
            {
                isConnection = ConnectionDB(this.ddlDBSource.SelectedValue.ToString());
            }
            #endregion
        }

        protected void ddlDBSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region
            switch (ddlDBSource.SelectedValue)
            {
                case "Oracle 8i/9i":
                    btnLoadDBConfig.Enabled = true;
                    fulFileUpload.Enabled = false;

                    txtHostName.Enabled = true;
                    txtProt.Enabled = true;
                    txtDBName.Enabled = true;
                    txtProt.Enabled = true;
                    txtUserName.Enabled = true;
                    txtPassWord.Enabled = true;

                    break;
                case "VPF":
                    btnLoadDBConfig.Enabled = false;
                    fulFileUpload.Enabled = true;

                    txtHostName.Enabled = false;
                    txtProt.Enabled = false;
                    txtDBName.Enabled = false;
                    txtProt.Enabled = false;
                    txtUserName.Enabled = false;
                    txtPassWord.Enabled = false;
                    break;
                case "Excel 2003":
                    btnLoadDBConfig.Enabled = false;
                    fulFileUpload.Enabled = true;

                    txtHostName.Enabled = false;
                    txtProt.Enabled = false;
                    txtDBName.Enabled = false;
                    txtProt.Enabled = false;
                    txtUserName.Enabled = false;
                    txtPassWord.Enabled = false;
                    break;
                case "Access":
                    btnLoadDBConfig.Enabled = false;
                    fulFileUpload.Enabled = true;

                    txtHostName.Enabled = false;
                    txtProt.Enabled = false;
                    txtDBName.Enabled = false;
                    txtProt.Enabled = false;
                    txtUserName.Enabled = false;
                    txtPassWord.Enabled = false;
                    break;
            }
            #endregion
        }

        protected void btnSaveConfig_Click(object sender, EventArgs e)
        {
            #region
            //保存配置信息
            dbConf.SaveConf(GetGridViewData(gvwDataTable));
            #endregion
        }

        #region 函数
        /// <summary>
        /// 把gvwdatatable中的第一列和最后一列数据添加到list中。
        /// </summary>
        /// <param name="gvw">gvwdatatable</param>
        /// <returns></returns>
        private List<ArrayList> GetGridViewData(GridView gvw)
        {
            #region
            List<ArrayList> laList = new List<ArrayList>();

            for (int i = 0; i < gvwDataTable.Rows.Count; i++)
            {
                ArrayList aList = new ArrayList();
                aList.Add(gvwDataTable.Rows[i].Cells[1].Text.ToString());

                DropDownList ddl = (DropDownList)(gvwDataTable.Rows[i].FindControl("DropDownList1"));
                aList.Add(ddl.SelectedValue.ToString());
                laList.Add(aList);
            }
            return laList;
            #endregion
        }

        private bool ConnectionDB(string DBType)
        {
            #region
            try
            {
                if (CheckPath(this.curUserID.ToString()) == false)
                {
                    return false;
                }
                switch (DBType)
                {
                    case "Oracle 8i/9i":
                        string filePath = GetClientDBConfigFileName(this.curUserID, DBType);
                        congInfo = GetDatabaseConInfo();
                        dbConf = new OracleConfigurature(congInfo, filePath);
                        break;
                    case "Access":
                        string filePath1 = GetClientDBConfigFileName(this.curUserID, DBType);
                        congInfo = GetFileInfo();
                        dbConf = new AccessConfigurature(congInfo, filePath1);
                        break;
                    case "VPF":
                        string filePath2 = GetClientDBConfigFileName(this.curUserID, DBType);
                        congInfo = GetFileInfo();
                        dbConf = new VPFConfigurature(congInfo, filePath2);
                        break;
                    case "Excel 2003":

                        congInfo = GetFileInfo();
                        dbConf = new ExcelConfigurature(congInfo);
                        break;
                    default:
                        break;
                }
                //只有按下一步或上一步进来的时候才能执行到其中
                //if (this.Session["isSelect"].ToString() == "0")
                //{
                //    InitializeTableSelectBox();
                //}

                return true;

            }
            catch (Exception ex)
            {
                JsAlert.Alert("连接数据库文件出错！");
                return false;
            }
            #endregion
        }

        /// <summary>
        /// 获得Oracle数据库连接信息
        /// </summary>
        /// <returns>返回字符串数组</returns>
        private string[] GetDatabaseConInfo()
        {
            #region
            string[] info = new string[6];
            info[0] = this.txtHostName.Text.Trim().ToString();//主机名
            info[1] = this.txtProt.Text.Trim().ToString();//端口号
            info[2] = this.txtDBName.Text.Trim().ToString();//数据库名
            info[3] = this.txtUserName.Text.Trim().ToString();//用户名
            if (this.txtPassWord.Text.Trim().ToString() == "")
            {
                info[4] = this.Session["dbpwd"].ToString();//密码
            }
            else
            {
                info[4] = this.txtPassWord.Text.Trim().ToString();
            }
            info[5] = curTableName;//当前数据表名
            return info;
            #endregion
        }

        /// <summary>
        /// 获取数据库文件名字串数组
        /// </summary>
        /// <returns></returns>
        private string[] GetFileInfo()
        {
            #region
            string[] info = new string[2];
            info[0] = hfdUploadFile.Value.ToString();
            info[1] = curTableName;
            return info;
            #endregion
        }



        /// <summary>
        /// 填充数据源ddl下拉列表框
        /// </summary>
        private void InitDataSource()
        {
            #region
            ddlDBSource.Items.Add("Oracle 8i/9i");
            ddlDBSource.Items.Add("VPF");
            ddlDBSource.Items.Add("Excel 2003");
            ddlDBSource.Items.Add("Access");
            #endregion
        }

        /// <summary>
        /// 检查当前用户在服务器上的clientdbconfig目录中自己的目录是否存在，如果不存在则创建它
        /// </summary>
        /// zxf
        /// <param name="UserID">用户id</param>
        /// <returns>成功返回true，否则返回false</returns>
        private bool CheckPath(string UserID)
        {
            #region
            string RootPath = this.Server.MapPath("../");
            RootPath = RootPath + "DataFile";

            try
            {
                DirectoryInfo DataFilePath = new DirectoryInfo(RootPath);       //服务器上数据文件目录
                if (DataFilePath.Exists == false)
                {
                    DataFilePath.Create();
                }

                RootPath = RootPath + "\\ClientDBConfig";

                DirectoryInfo clientDBConfigPath = new DirectoryInfo(RootPath);     //服务器上存放用户客户端数据库配置的文件夹
                if (clientDBConfigPath.Exists == false)
                {
                    clientDBConfigPath.Create();
                }

                RootPath = RootPath + "\\" + UserID.ToString();                 //用户自己的目录（用户id）

                DirectoryInfo CurUserPath = new DirectoryInfo(RootPath);
                if (CurUserPath.Exists == false)
                {
                    CurUserPath.Create();
                }

            }
            catch (IOException ioex)
            {
                JsAlert.Alert("对读写服务器目录出错！");
                return false;
            }

            return true;
            #endregion
        }

        /// <summary>
        /// 检查用户的数据库配置文件是否存在
        /// </summary>
        /// <param name="UserID">用户id</param>
        /// <param name="DBType">数据库类型</param>
        /// <returns>存在返回true，否则返回false</returns>
        private bool isCheckConfigFile(string UserID, string DBType)
        {
            #region
            string sPath = GetClientDBConfigFileName(UserID, DBType).Trim().ToString();
            if (sPath != "")
            {
                FileInfo fileInfo = new FileInfo(sPath);
                if (fileInfo.Exists == true)
                {
                    return true;
                }

            }
            return false;
            #endregion
        }
        /// <summary>
        /// 检查用户的数据库配置文件是否存在
        /// </summary>
        private bool isCheckConfigFile()
        {
            #region
            switch (ddlDBSource.SelectedValue.Trim().ToString())
            {
                case "Oracle 8i/9i":
                    return isCheckConfigFile(curUserID, "orl");
                case "VPF":
                    return isCheckConfigFile(curUserID, "vpf");
                case "Excel 2003":
                    return isCheckConfigFile(curUserID, "exl");
                default:
                    return false;
            }
            #endregion
        }

        /// <summary>
        /// 获得当前用户配置文件全路径
        /// </summary>
        /// <param name="UserID">当前用户id</param>
        /// <param name="DBType">数据库类型</param>
        /// <returns>返回当前用户配置文件全路径</returns>
        private string GetClientDBConfigFileName(string UserID, string DBType)
        {
            #region
            string WebRootPath = this.Server.MapPath("../../");

            WebRootPath = WebRootPath + "SJCJDataFile\\ClientDBConfig\\" + UserID.ToString();
            switch (DBType)
            {
                case "Oracle 8i/9i":
                    WebRootPath = WebRootPath + "\\orl.xml";
                    break;
                case "Access":
                    WebRootPath = WebRootPath + "\\access.xml";
                    break;
                case "VPF":
                    WebRootPath = WebRootPath + "\\vpf.xml";
                    break;
                case "Excel 2003":
                    WebRootPath = WebRootPath + "\\exl.xml";
                    break;
                default:
                    break;
            }
            return WebRootPath;
            #endregion
        }


        /// <summary>
        /// 初始化表选择列表框
        /// </summary>
        private void InitializeTableSelectBox()
        {
            #region
            this.ddlDBTable.DataSource = null;
            //this.gvwDataTable.DataSource = null;
            //this.gvwDataTable.Columns.Clear();
            this.ddlDBTable.Items.Clear();
            this.ddlDBTable.DataSource = dbConf.GetTableScama();
            this.ddlDBTable.DataBind();
            #endregion

        }
       
        /// <summary>
        /// 获得本地表字段
        /// </summary>
        /// <returns></returns>
        private string GetSrcFieldList()
        {
            #region
            StringBuilder sb = new StringBuilder();
            int count = gvwDataTable.Rows.Count - 1;
            object colName = null;
            for (int i = 0; i < count; i++)
            {
                DropDownList ddl = (DropDownList)gvwDataTable.Rows[i].FindControl("DropDownList1");
                colName = ddl.SelectedValue.ToString().ToLower();
                if (colName != null && colName.ToString().Trim() != "")
                {
                    sb.Append(colName.ToString() + ",");
                }
            }

            DropDownList ddlColName = (DropDownList)gvwDataTable.Rows[count].FindControl("DropDownList1");
            colName = ddlColName.SelectedValue.ToString().ToLower();

            if (colName != null && colName.ToString().Trim() != "")
            {
                sb.Append(colName.ToString());
            }
            else if (sb.Length > 1)
            {
                sb.Remove(sb.Length - 1, 1);
            }

            //如果sb为空，可能是通过加载字段配置文件过来的。
            if (sb.ToString().Trim() == "")
            {
                for (int i = 0; i < gvwDataTable.Rows.Count; i++)
                {
                    string sValue = gvwDataTable.Rows[i].Cells[6].Text.Trim().ToString();
                    if (sValue != "")
                    {
                        if (i == 0)
                        {
                            sb.Append(sValue);
                        }
                        else
                        {
                            sb.Append("," + sValue);
                        }
                    }

                }
            }

            return sb.ToString();
            #endregion
        }


        #endregion

        /// <summary>
        /// 第一页的下一步按钮点击事件
        /// </summary>
        protected void btnNext1_Click(object sender, EventArgs e)
        {
            #region
            bool isConnection;

            //CurStep = Convert.ToInt32(this.Session["CurStep"].ToString()) + 1;
            //this.Session["CurStep"] = (object)CurStep;
            CurStep = 2;
            string sFileName = "";
            string sFileType = "";
            //判断数据完整性
            switch (ddlDBSource.SelectedValue.Trim().ToString())
            {
                case "Oracle 8i/9i":
                    if (txtDBName.Text.Trim().ToString() == "" || txtHostName.Text.Trim().ToString() == "" || txtProt.Text.Trim().ToString() == "" || txtUserName.Text.Trim().ToString() == "" || txtPassWord.Text.Trim().ToString() == "")
                    {
                        JScript.Alert(this, "数据不完整！");
                        return;
                    }
                    btnLoadFieldConfig.Enabled = true;
                    btnSaveConfig.Enabled = true;
                    break;
                case "Access":
                    sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                    if (sFileName == "")
                    {
                        JScript.Alert(this, "请选择本地数据文件。");
                        return;
                    }
                    sFileType = sFileName.Substring(sFileName.Length - 4);
                    if (sFileType != ".mdb")
                    {
                        JScript.Alert(this.Page, "文件格式不对,请选择Access文件！");
                        return;
                    }
                    btnLoadFieldConfig.Enabled = false;
                    btnSaveConfig.Enabled = false;
                    break;
                case "VPF":
                    sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                    if (sFileName == "")
                    {
                        JScript.Alert(this, "请选择本地数据文件！");
                        return;
                    }
                    sFileType = sFileName.Substring(sFileName.Length - 4);
                    if (sFileType != ".dbf")
                    {
                        JScript.Alert(this.Page, "文件格式不对,请选择vfp数据文件！");
                        return;
                    }
                    btnLoadFieldConfig.Enabled = false;
                    btnSaveConfig.Enabled = false;
                    break;
                case "Excel 2003":
                    sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                    if (sFileName == "")
                    {
                        JScript.Alert(this, "请选择本地数据文件。");
                        return;
                    }
                    sFileType = sFileName.Substring(sFileName.Length - 4);
                    if (sFileType != ".xls")
                    {
                        JScript.Alert(this.Page, "文件格式不对,请选择Excel 2003文件！");
                        return;
                    }
                    btnLoadFieldConfig.Enabled = false;
                    btnSaveConfig.Enabled = false;
                    break;
                default:
                    break;
            }
            //保存本地数据文件全名到隐藏控件中
            if (ddlDBSource.SelectedValue.ToString() != "Oracle 8i/9i")
            {
                //上传数据文件
                //string filePath = fulFileUpload.PostedFile.FileName.Trim().ToString();
                //string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                string serverPath = Server.MapPath("../../SJCJDataFile/DBFile/") + sFileName;
                fulFileUpload.PostedFile.SaveAs(serverPath);
                hfdUploadFile.Value = serverPath;
            }
            //在第二步中使用 连接数据库和填充表名
            isConnection = ConnectionDB(this.ddlDBSource.SelectedValue.ToString());
            InitializeTableSelectBox();
            this.Session.Add("dbpwd", txtPassWord.Text.Trim().ToString());
            plMatchField.Visible = true;
            plNoMatchField.Visible = false;
            btnNext2.Enabled = false;
            btnNoMatchField.Enabled = false;
            Wizard1.ActiveStepIndex = 1;
            #endregion
        }
        /// <summary>
        /// 根据选择的表，加载服务器表和客户端表字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLoadGridView_Click(object sender, EventArgs e)
        {
            #region
            if (this.ddlDBTable.SelectedValue.Trim() == "")
            {
                JScript.Alert(this.Page, "数据表不能为空!");
                return;
            }

            this.Session["isSelect"] = "1";                     //表明是从按钮事件来的

            if (this.ddlDBTable.SelectedIndex != -1)
            {
                if (sList != null)
                {
                    sList.Clear();
                }
                sList = dbConf.GetColumnsScama(ddlDBTable.SelectedValue.ToString());
                sList.Add("");
                this.Session["srcfields"] = sList;

                if (gvwDataTable.DataSource == null)
                {
                    //绑定数据
                  InitializeFieldMapping();
                }
                else
                {
                    //重新绑定模板列
                    for (int i = 0; i < gvwDataTable.Rows.Count; i++)
                    {
                        DropDownList ddl = (DropDownList)(gvwDataTable.Rows[i].FindControl("ddlGridView"));
                        ddl.DataSource = sList;
                        ddl.DataBind();
                    }
                }

                int count1 = gvwDataTable.Rows.Count;
                int count2 = sList.Count;
                bool isSame = false;

                int colCount = gvwDataTable.Columns.Count - 1;
                string value = null;
                //if (lstNotNullFields != null)
                //{
                //    lstNotNullFields.Clear();
                //}

                for (int i = 0; i < count1; i++)
                {
                    isSame = false;
                    DropDownList ddl = (DropDownList)(gvwDataTable.Rows[i].FindControl("DropDownList1"));
                    for (int j = 0; j < count2; j++)
                    {
                        value = sList[j].ToString();


                        if (gvwDataTable.Rows[i].Cells[1].Text.ToString().ToUpper() == value.ToUpper())
                        {
                            //自动匹配相同的字段

                            ddl.SelectedValue = value;
                            isSame = true;
                            break;
                        }

                    }
                    //为不匹配的字段设置颜色
                    if (isSame == false)
                    {
                        gvwDataTable.Rows[i].BackColor = Color.CornflowerBlue;// '#D6F1F8';
                        ddl.SelectedValue = "";
                    }
                    //把不为空的字段添加到session中
                    //if (gvwDataTable.Rows[i].Cells[4].Text.Trim().ToString().ToLower() == "n")
                    //{
                    //    lstNotNullFields.Add(gvwDataTable.Rows[i].Cells[1].Text.Trim().ToString());
                    //}
                }
                //this.Session["notnullfields"] = lstNotNullFields;
            }

            btnNoMatchField.Enabled = true;
            plMatchField.Visible = true;
            plNoMatchField.Visible = false;
            btnNext2.Enabled = true;
            initalSaveOrLoadFieldConfig(ddlDBSource.SelectedValue.Trim().ToString());
           
            #endregion
        }
        protected void initalSaveOrLoadFieldConfig(string type)
        { 
            if (type == "Excel 2003")
            {
                btnSaveConfig.Enabled = false;
                btnLoadFieldConfig.Enabled = false;
            }
            if (type == "Access")
            {
                btnSaveConfig.Enabled = false;
                btnLoadFieldConfig.Enabled = false;
            }
            if (type == "Oracle 8i/9i")
            {
                btnSaveConfig.Enabled = true;
                btnLoadFieldConfig.Enabled = true;
            }
            if (type == "VPF")
            {
                btnSaveConfig.Enabled = true;
                btnLoadFieldConfig.Enabled = true;
            }
        }

        protected void gvwDataTable_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            #region
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //修改显示信息
                string col3 = e.Row.Cells[3].Text.ToString().Trim();            //类型
                string col4 = e.Row.Cells[4].Text.ToString().Trim();            //为空
                string col5 = e.Row.Cells[5].Text.ToString().Trim();            //主键
                switch (col3)
                {
                    //文本类
                    case "C":
                        {
                            e.Row.Cells[3].Text = "VARCHAR2()";
                            break;
                        }
                    //浮点类
                    case "N":
                        {
                            e.Row.Cells[3].Text = "NUMBER()";
                            break;
                        }
                    //日期类
                    case "D":
                        {
                            e.Row.Cells[3].Text = "date";
                            break;
                        }
                    //时间类
                    case "T":
                        {
                            e.Row.Cells[3].Text = "datetime";
                            break;
                        }
                }
                if (col4 == "1")
                {
                    e.Row.Cells[4].Text = "否";
                }
                else
                {
                    e.Row.Cells[4].Text = "是";
                }
                if (col5 == "1")
                {
                    e.Row.Cells[5].Text = "是";
                }
                else
                {
                    e.Row.Cells[5].Text = "否";
                }

                //绑定模板列数据
                DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
                ddl.DataSource = sList;
                ddl.DataBind();
            }
            #endregion
        }

        // 加载上次数据库配置
        protected void btnLoadDBConfig_Click(object sender, EventArgs e)
        {
            #region
            string fileName = GetClientDBConfigFileName(curUserID, ddlDBSource.SelectedValue.Trim().ToString());
            FileInfo confFile = new FileInfo(fileName);
            if (!confFile.Exists)
            {
                JScript.Alert(this, "配置文件不存在!");
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);
                XmlNodeList oraNodes = doc.GetElementsByTagName("Oracle-Conf");

                if (oraNodes.Count > 0)
                {
                    XmlNode oraNode = oraNodes[0];
                    XmlAttributeCollection attributes = oraNode.Attributes;
                    txtHostName.Text = attributes["host_name"].Value.ToString();
                    txtProt.Text = attributes["port_number"].Value.ToString();
                    txtDBName.Text = attributes["instance_name"].Value.ToString();
                    txtUserName.Text = attributes["user_name"].Value.ToString();
                    //txtPassWord.Attributes["value"] = DQYT.HTDZ.BusinessService.OracleConfigurature.Dcode(attributes["password"].Value.ToString());
                    txtPassWord.Attributes["value"] = StandardService.Dcode(attributes["password"].Value.ToString());//解码
                }
                else
                {
                    JScript.Alert(this, "配置文件错误，请重新生成");
                }
            }
            #endregion
        }

        protected void btnPrevious2_Click(object sender, EventArgs e)
        {
            #region
            CurStep = Convert.ToInt32(this.Session["CurStep"].ToString()) - 1;
            this.Session["CurStep"] = (object)CurStep;
            //VisibleEnabled(CurStep);
            txtPassWord.Attributes["value"] = this.Session["dbpwd"].ToString();

            Wizard1.ActiveStepIndex = 0;
            #endregion
        }
        //加载字段配置文件
        protected void btnLoadFieldConfig_Click(object sender, EventArgs e)
        {
            dbConf.LoadConf(ddlDBTable, gvwDataTable);
        }

        protected void gvwDataTable_DataBound(object sender, EventArgs e)
        {
            #region
            //string str = gvwDataTable.Rows[0].Cells[0].Text.ToString();
            //string str1 = gvwDataTable.Rows[0].Cells[1].Text.ToString();
            if (gvwDataTable.Rows[0].Cells[1].Text.ToLower().Replace("&nbsp;", "") == "")
            {
   /////////////////////////////             WebUI.ShowNoResultRow(gvwDataTable.Rows[0]);
            }
            #endregion
        }


        #region 第三页函数
        /// <summary>
        /// 设置查询条件井号的可用性
        /// </summary>
        /// <param name="isTrue">是否可用</param>
        private void WellEnabled(bool isTrue)
        {
            #region
            ddlWellNo.Enabled = isTrue;
            ddlWellOpera.Enabled = isTrue;
            txtWell.Enabled = isTrue;
            #endregion
        }
        /// <summary>
        /// 设置时间查询条件控件的可用性
        /// </summary>
        /// <param name="isTrue">是否可用</param>
        private void LoadDataEnabled(bool isTrue)
        {
            #region
            ddlLoadDate.Enabled = isTrue;
            txtBeginDate.Enabled = isTrue;
            txtEndDate.Enabled = isTrue;
            #endregion
        }
        /// <summary>
        /// 设置自定义查询条件控件的可用性
        /// </summary>
        /// <param name="isTrue">是否可用</param>
        private void CustomEnabled(bool isTrue)
        {
            #region
            ddlFieldName.Enabled = isTrue;
            ddlFieldOpera.Enabled = isTrue;
            txtFieldValue.Enabled = isTrue;
            btnAddSQL.Enabled = isTrue;
            #endregion
        }
        /// <summary>
        /// 设置全筛选条件控件的可用性
        /// </summary>
        /// <param name="isTrue"></param>
        private void AllDataFilter(bool isTrue)
        {
            #region
            if (isTrue == true)
            {
                //btnAccomplish.Enabled = true;
                //btnClear.Enabled = false;
                //btnMakeSQL.Enabled = false;
                chkWellNo.Enabled = false;
                WellEnabled(false);
                chkLoadDate.Enabled = false;
                LoadDataEnabled(false);
                chkCustom.Enabled = false;
                CustomEnabled(false);
            }
            else
            {
                //btnClear.Enabled = true ;
                //btnMakeSQL.Enabled = true ;
                chkWellNo.Enabled = true;
                if (chkWellNo.Checked == true)
                {
                    WellEnabled(true);
                }
                chkLoadDate.Enabled = true;
                if (chkLoadDate.Checked == true)
                {
                    LoadDataEnabled(true);
                }
                chkCustom.Enabled = true;
                if (chkCustom.Checked == true)
                {
                    CustomEnabled(true);
                }
            }
            #endregion
        }

        /// <summary>
        /// 生成查询SQL
        /// </summary>
        /// <returns></returns>
        private string MakeSQL()
        {
            #region
            bool isChecked = false;
            string str = "";
            string sSQL = this.Session["srctablesql"].ToString();
            if (radlDataFilter.SelectedValue.Trim().ToString() == "追加全部")
            {
                return sSQL;
            }
            else
            {
                if (chkWellNo.Checked == true)
                {
                    isChecked = true;
                    sSQL = sSQL + " WHERE ";
                    str = " (" + ddlWellNo.SelectedValue.Trim().ToString() + " "
                        + ddlWellOpera.SelectedValue.Trim().ToString();
                    if (ddlWellOpera.SelectedValue.Trim().ToString() == "like")
                    {
                        str = str + " '%" + txtWell.Text.Trim().ToString() + "%') ";
                    }
                    else
                    {
                        str = str + " '" + txtWell.Text.Trim().ToString() + "') ";
                    }

                    sSQL = sSQL + str;
                }
                if (chkLoadDate.Checked == true)
                {
                    str = " ( " + ddlLoadDate.SelectedValue.Trim().ToString() +
                            " BETWEEN to_date('" + txtBeginDate.Text.Trim().ToString() + "','yyyy-MM-dd') and to_date('" +
                            txtEndDate.Text.Trim().ToString() + "','yyyy-MM-dd')) ";
                    if (isChecked == true)
                    {
                        sSQL = sSQL + " AND " + str;
                    }
                    else
                    {
                        isChecked = true;
                        sSQL = sSQL + " WHERE " + str;
                    }


                }
                if (chkCustom.Checked == true)
                {
                    lstSQL = (List<string>)this.Session["lstsql"];
                    if (lstSQL.Count > 0)
                    {
                        if (isChecked == true)
                        {
                            for (int i = 0; i < lstSQL.Count; i++)
                            {
                                sSQL = sSQL + " AND " + lstSQL[i].ToString();
                            }
                        }
                        else
                        {
                            for (int i = 0; i < lstSQL.Count; i++)
                            {
                                if (i == 0)
                                {
                                    sSQL = sSQL + " WHERE " + lstSQL[i].ToString();
                                }
                                else
                                {
                                    sSQL = sSQL + " AND " + lstSQL[i].ToString();
                                }

                            }
                        }

                    }
                }
                return sSQL;
            }
            #endregion
        }

        /// <summary>
        /// 获得数据库连接配置信息
        /// </summary>
        private List<string> GetCongInfo()
        {
            #region
            List<string> listDBConfig = new List<string>();

            switch (ddlDBSource.SelectedValue.Trim().ToString())
            {
                case "Oracle 8i/9i":

                    listDBConfig.Add("orl");
                    listDBConfig.Add(txtHostName.Text.Trim().ToString());
                    listDBConfig.Add(txtProt.Text.Trim().ToString());
                    listDBConfig.Add(txtDBName.Text.Trim().ToString());
                    listDBConfig.Add(txtUserName.Text.Trim().ToString());
                    listDBConfig.Add(this.Session["dbpwd"].ToString());
                    listDBConfig.Add(ddlDBTable.SelectedValue.ToString());

                    break;
                case "VPF":
                    listDBConfig.Add("vpf");
                    listDBConfig.Add(hfdUploadFile.Value.ToString());
                    listDBConfig.Add(ddlDBTable.SelectedValue.ToString());
                    break;
                case "Excel 2003":
                    listDBConfig.Add("exl");
                    listDBConfig.Add(hfdUploadFile.Value.ToString());
                    listDBConfig.Add(ddlDBTable.SelectedValue.ToString());
                    break;
                case "Access":
                    listDBConfig.Add("mdb");
                    listDBConfig.Add(hfdUploadFile.Value.ToString());
                    listDBConfig.Add(ddlDBTable.SelectedValue.ToString());
                    break;
                default:
                    break;
            }
            return listDBConfig;
            #endregion
        }

        /// <summary>
        /// 保存两表的字段对应关系
        /// </summary>
        private List<ArrayList> Save2FieldInfo()
        {
            #region
            List<ArrayList> listArrayList = new List<ArrayList>();

            for (int i = 0; i < gvwDataTable.Rows.Count; i++)
            {
                DropDownList ddl = (DropDownList)gvwDataTable.Rows[i].FindControl("DropDownList1");
                if (ddl.SelectedValue.Trim().ToString() != "")
                {
                    ArrayList arrayList = new ArrayList();
                    string dtColName = gvwDataTable.Rows[i].Cells[1].Text.ToString();
                    arrayList.Add(dtColName);
                    arrayList.Add(ddl.SelectedValue.Trim().ToString());
                    listArrayList.Add(arrayList);
                }
            }

            //如果listArrayList为空，则有可能是从点击加载字段配置文件过来的。
            if (listArrayList.Count == 0)
            {
                for (int i = 0; i < gvwDataTable.Rows.Count; i++)
                {
                    string sValue = gvwDataTable.Rows[i].Cells[6].Text.Trim().ToString();
                    if (sValue != "")
                    {
                        ArrayList arrayList = new ArrayList();
                        string dtColName = gvwDataTable.Rows[i].Cells[1].Text.ToString();
                        arrayList.Add(dtColName);
                        arrayList.Add(sValue);
                        listArrayList.Add(arrayList);
                    }
                }
            }
            return listArrayList;
            #endregion
        }

        #endregion

        protected void chkWellNo_CheckedChanged(object sender, EventArgs e)
        {
            #region
            if (chkWellNo.Checked == true)
            {
                WellEnabled(true);
            }
            else
            {
                WellEnabled(false);
            }
            #endregion
        }

        protected void chkLoadDate_CheckedChanged(object sender, EventArgs e)
        {
            #region
            if (chkLoadDate.Checked == true)
            {
                LoadDataEnabled(true);
            }
            else
            {
                LoadDataEnabled(false);
            }
            #endregion
        }

        protected void chkCustom_CheckedChanged(object sender, EventArgs e)
        {
            #region
            if (chkCustom.Checked == true)
            {
                CustomEnabled(true);
            }
            else
            {
                CustomEnabled(false);
            }
            #endregion
        }

        protected void radlDataFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region
            if (radlDataFilter.SelectedValue.Trim().ToString() == "追加全部")
            {
                AllDataFilter(true);
                //btnAccomplish.Enabled = true;
                //btnMakeSQL.Enabled = false;
            }
            else
            {
                AllDataFilter(false);
                btnAccomplish.Enabled = false;
                //btnMakeSQL.Enabled = true;
            }
            #endregion
        }

        /// <summary>
        /// 检查不可为空字段是否有对应字段
        /// </summary>
        /// <returns>都存在对应字段返回true，否则返回false</returns>
        private bool CheckNotNullSrcField()
        {
            #region
            for (int i = 0; i < gvwDataTable.Rows.Count; i++)
            {
                if (gvwDataTable.Rows[i].Cells[4].Text.Trim().ToString().ToUpper() == "否" || gvwDataTable.Rows[i].Cells[5].Text.Trim().ToString().ToUpper() == "是")
                {
                    DropDownList ddl = (DropDownList)gvwDataTable.Rows[i].FindControl("DropDownList1");
                    string sValue = gvwDataTable.Rows[i].Cells[6].Text.Trim().ToString();
                    if (ddl.SelectedValue.Trim().ToString() == "" && sValue == "")
                    {
                        return false;
                    }
                }

            }
            return true;
            #endregion
        }

        protected void btnNext2_Click(object sender, EventArgs e)
        {
            #region
            //检查不可为空的字段是否有对应的字段
            if (CheckNotNullSrcField() == false)
            {
                JScript.Alert(this, "主键字段和不可为空字段必须有相对应的字段!");
                return;
            }
            //获得本地表字段
            string sFieldList = GetSrcFieldList();
            sSrcTableSQL = "SELECT " + sFieldList + " FROM " + ddlDBTable.SelectedValue.ToString();
            this.Session["srctablesql"] = sSrcTableSQL;
            //保存对应字段信息
            Save2FieldInfo();

            //初始化数据
            ddlWellNo.DataSource = (List<string>)this.Session["srcfields"];
            ddlWellNo.DataBind();
            ddlLoadDate.DataSource = (List<string>)this.Session["srcfields"];
            ddlLoadDate.DataBind();
            ddlFieldName.DataSource = (List<string>)this.Session["srcfields"];
            ddlFieldName.DataBind();
            //初始化按钮状态
            if (radlDataFilter.SelectedValue.Trim().ToString() == "追加全部")
            {
                AllDataFilter(true);
            }
            else
            {
                AllDataFilter(false);
                btnAccomplish.Enabled = false;
            }
            Wizard1.ActiveStepIndex = 2;
            #endregion
        }

        protected void btnPrevious3_Click(object sender, EventArgs e)
        {
            #region
            Wizard1.ActiveStepIndex = 1;
            #endregion
        }

        protected void btnMakeSQL_Click(object sender, EventArgs e)
        {
            #region
            if (radlDataFilter.SelectedValue.ToString() == "追加全部")
            {
                string sSQL = this.Session["srctablesql"].ToString();
                txtMakeSQL.Text = sSQL;
                btnAccomplish.Enabled = true;
                return;
            }

            if (chkWellNo.Checked == true)
            {
                if (ddlWellNo.SelectedValue.Trim().ToString() == "" || ddlWellOpera.SelectedValue.Trim().ToString() == "" || txtWell.Text.Trim().ToString() == "")
                {
                    JScript.Alert(this, "请完善井号查询条件!");
                    return;
                }
            }
            if (chkLoadDate.Checked == true)
            {
                if (ddlLoadDate.SelectedValue.Trim().ToString() == "" || txtBeginDate.Text.Trim().ToString() == "" || txtEndDate.Text.Trim().ToString() == "")
                {
                    JScript.Alert(this, "请完善日期查询条件!");
                    return;
                }
                else
                {
                    DateTime dtBegin = System.Convert.ToDateTime(txtBeginDate.Text.Trim().ToString());
                    DateTime dtEnd = System.Convert.ToDateTime(txtEndDate.Text.Trim().ToString());
                    if (dtBegin > DateTime.Today || dtEnd > DateTime.Today)
                    {
                        JScript.Alert(this, "查询日期不能大于当前日期!");
                        return;
                    }
                    if (dtBegin > dtEnd)
                    {
                        JScript.Alert(this, "开始日期不能大于结束日期!");
                        return;
                    }
                }
            }
            txtMakeSQL.Text = MakeSQL();
            btnAccomplish.Enabled = true;
            //btnClear.Enabled = true;
            #endregion
        }

        protected void btnAddSQL_Click(object sender, EventArgs e)
        {
            #region
            if (chkCustom.Checked == true)
            {
                if (ddlFieldName.SelectedValue.Trim().ToString() == "")
                {
                    JScript.Alert(this, "请选择字段！");
                    ddlFieldName.Focus();
                    return;
                }
                if (ddlFieldOpera.SelectedValue.Trim().ToString() == "")
                {
                    JScript.Alert(this, "请选择查询条件！");
                    ddlFieldOpera.Focus();
                    return;
                }
                if (txtFieldValue.Text.Trim().ToString() == "")
                {
                    JScript.Alert(this, "请填写查询值！");
                    txtFieldValue.Focus();
                    return;
                }
                string sSQL = " (" + ddlFieldName.SelectedValue.Trim().ToString() + " "
                    + ddlFieldOpera.SelectedValue.Trim().ToString();

                if (ddlFieldOpera.SelectedValue.Trim().ToString() == "like")
                {
                    sSQL = sSQL + " '%" + txtFieldValue.Text.Trim().ToString() + "%') ";
                }
                else
                {
                    sSQL = sSQL + " '" + txtFieldValue.Text.Trim().ToString() + "') ";
                }

                lstSQL = (List<string>)this.Session["lstsql"];
                lstSQL.Add(sSQL);
                this.Session["lstsql"] = lstSQL;
                JScript.Alert(this, "条件已添加！");
                txtFieldValue.Text = "";
            }
            #endregion
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            #region
            lstSQL.Clear();
            this.Session["lstsql"] = lstSQL;
            //btnMakeSQL.Enabled = true;
            txtMakeSQL.Text = "";
            btnAccomplish.Enabled = false;
            #endregion
        }

        protected void btnAccomplish_Click(object sender, EventArgs e)
        {
            #region
            //把链接信息对象、字段对应信息对象、数据源对象通过session发送到父页面。
            this.Session["resultsql"] = txtMakeSQL.Text.Trim().ToString();
            this.Session["srcdb"] = GetCongInfo();
            this.Session["oppfields"] = Save2FieldInfo();

            //清理session
            this.Session["CurStep"] = "";
            this.Session["isSelect"] = "";
            this.Session["srctablesql"] = "";
            this.Session["srcfields"] = "";
            this.Session["lstsql"] = "";
            //返回父页面一个值Y
            string strScript = "<script language=javascript>top.window.returnValue=";

            strScript += "\"Y\"" + ";top.window.close(this);</script>";

            Response.Write(strScript);
            #endregion
        }

        /// <summary>
        /// 查看服务器表和本地表字段匹配信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNoMatchField_Click(object sender, EventArgs e)
        {
            #region
            plMatchField.Visible = false;
            plNoMatchField.Visible = true;

            DataTable dt = GetMatchFieldInfo();

            gvwField.DataSource = dt;
            gvwField.DataBind();
            #endregion
        }

        /// <summary>
        /// 获得服务器表和本地表字段匹配信息
        /// </summary>
        /// <returns></returns>
        private DataTable GetMatchFieldInfo()
        {
            #region
            int iOkNum = 0;                     //正确匹配字段数
            int iNoServerNum = 0;               //服务器字段不匹配字段数
            int iNoClientNum = 0;               //本地表字段不匹配数
            //int iNoFieldNum = 0;
            List<string> listOKField = new List<string>();
            sList = (List<string>)this.Session["srcfields"];
            int iServerFieldNum = gvwDataTable.Rows.Count;
            int iClientFieldNum = sList.Count - 1;

            //初始化表结构
            DataTable dt = new DataTable();
            dt.Columns.Add("ServerField", typeof(string));
            dt.Columns.Add("ServerFieldNum", typeof(string));
            dt.Columns.Add("ClientField", typeof(string));
            dt.Columns.Add("ClientFieldNum", typeof(string));
            //总字段数
            DataRow dr = dt.NewRow();

            dr[0] = "需匹配字段总数：";
            dr[1] = iServerFieldNum.ToString();
            dr[2] = "字段总数：";
            dr[3] = iClientFieldNum.ToString();
            dt.Rows.Add(dr);

            //把所有值都转换为小写形式
            for (int i = 0; i < sList.Count; i++)
            {
                sList[i] = sList[i].ToLower();
            }

            for (int i = 0; i < iServerFieldNum; i++)
            {
                if (sList.Contains(gvwDataTable.Rows[i].Cells[1].Text.ToLower().ToString()))
                {
                    listOKField.Add(gvwDataTable.Rows[i].Cells[1].Text.ToLower().ToString());
                }
            }

            iOkNum = listOKField.Count;
            iNoServerNum = iServerFieldNum - iOkNum;
            iNoClientNum = iClientFieldNum - iOkNum;

            //添加正确匹配的字段行
            DataRow dr1 = dt.NewRow();
            dr1[0] = "正确匹配字段数：";
            dr1[1] = iOkNum.ToString();
            dr1[2] = "正确匹配字段数：";
            dr1[3] = iOkNum.ToString();
            dt.Rows.Add(dr1);
            //添加不匹配的字段行
            DataRow dr2 = dt.NewRow();
            dr2[0] = "不匹配字段数：";
            dr2[1] = iNoServerNum.ToString();
            dr2[2] = "不匹配字段数：";
            dr2[3] = iNoClientNum.ToString();
            dt.Rows.Add(dr2);
            //添加不匹配字段名
            DataRow dr3 = dt.NewRow();
            dr3[0] = "不匹配字段：";
            dr3[1] = "";
            dr3[2] = "不匹配字段：";
            dr3[3] = "";
            dt.Rows.Add(dr3);

            int iCurNum = 0;
            //添加不匹配的字段名到表中
            if (iNoServerNum > iNoClientNum)
            {
                iCurNum = 0;
                for (int m = 0; m < iServerFieldNum; m++)
                {
                    if (!listOKField.Contains(gvwDataTable.Rows[m].Cells[1].Text.ToLower().ToString()))
                    {
                        DataRow dr4 = dt.NewRow();
                        dr4[0] = gvwDataTable.Rows[m].Cells[2].Text.ToLower().ToString();
                        dr4[1] = gvwDataTable.Rows[m].Cells[1].Text.ToLower().ToString();
                        dt.Rows.Add(dr4);
                    }
                }

                for (int h = 0; h < iClientFieldNum; h++)
                {
                    if (!listOKField.Contains(sList[h].ToString().ToLower()))
                    {
                        dt.Rows[4 + iCurNum][3] = sList[h].ToString().ToLower();
                        iCurNum = iCurNum + 1;
                    }
                }
            }
            else
            {
                for (int h = 0; h < iClientFieldNum; h++)
                {
                    if (!listOKField.Contains(sList[h].ToString().ToLower()))
                    {
                        DataRow dr4 = dt.NewRow();
                        dr4[3] = sList[h].ToString().ToLower();
                        dt.Rows.Add(dr4);
                    }
                }
                iCurNum = 0;
                for (int m = 0; m < iServerFieldNum; m++)
                {
                    if (!listOKField.Contains(gvwDataTable.Rows[m].Cells[1].Text.ToLower().ToString()))
                    {
                        dt.Rows[4 + iCurNum][0] = gvwDataTable.Rows[m].Cells[2].Text.ToLower().ToString();
                        dt.Rows[4 + iCurNum][1] = gvwDataTable.Rows[m].Cells[1].Text.ToLower().ToString();
                        iCurNum = iCurNum + 1;
                    }
                }
            }

            return dt;
            #endregion
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            #region
            plMatchField.Visible = true;
            plNoMatchField.Visible = false;
            #endregion
        }
        /// <summary>
        /// 下载字段匹配信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownloadField_Click(object sender, EventArgs e)
        {
            #region
            DataTable dt = new DataTable();
            dt = GetMatchFieldInfo();

   /////////////////         JrscSoft.BusinessService.LogAdminService.AddLogDataLog(this.Session["UserName"].ToString(), Session["IP"].ToString(), "", "", "基础数据", "字段对应信息，服务器表：" + curTableName.ToString() + ",本地表：" + ddlDBTable.Text.ToString(), "下载", "", "数据源配置");

   ////////////////////         JrscSoft.Common.Ins_ToExcel toExcel = new JrscSoft.Common.Ins_ToExcel();
            //////////////////toExcel.ToExcel(dt, curTableName.ToString(), "字段对应信息-服务器表：" + curTableName.ToString() + ",本地表：" + ddlDBTable.Text.ToString(), System.DateTime.Today.ToString());
            #endregion
        }
        /// <summary>
        /// 密码输入框内容改变时触发该事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPassWord_TextChanged(object sender, EventArgs e)
        { 

        }
        /// <summary>
        /// 文件上传内容框内容改变时触发该事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hfdUploadFile_ValueChanged(object sender, EventArgs e)
        { 

        }
        /// <summary>
        /// 表格绑定数据
        /// </summary>
        private void InitializeFieldMapping()
        {
            #region
            try
            {

                BDDICTBLL dictBll = new BDDICTBLL();
                DataSet ds = dictBll.GetList_TableCode(curTableName);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                }
                gvwDataTable.DataSource = ds;
                gvwDataTable.DataBind();
            }
            catch (Exception ex)
            {
                JScript.Alert(this, "表格加载数据出错！错误信息：" + ex.Message.ToString());
            }
            #endregion

        }


     
    }
}
